<template>
  <base-breadcrumb :title="titleName">
    <searchData :search-data="searchArr" @search="search" />
    <a-card :bordered="false">
      <!-- <title-name title="分包商季度考核列表" /> -->
      <list-table
        ref="table"
        :columns="columns"
        :exportConfig="{ use: true, select: '分包商季度考核', all: '分包商季度考核', customColumns }"
        :exportConfigText="{ select: '导出选中', all: '导出全部' }"
        :request="loadData"
        :isShowTotal="false"
        :filterData="filterData"
        :statisticsConfig="{ use: true, statistics, temp }"
      >
        <template slot="prefix" slot-scope="ref">
          <a-button type="primary" v-if="isShowBatchBtn" @click="goBatch" :disabled="$refs.table && $refs.table.tableData.length === 0">批量考核 </a-button>
          <BasePrintButton ref="BasePrintButton" style="display: inline-block;" type="primary" buttonText="批量打印" :before-print-fn="handleBatchPrint" />
          <!-- <a-button type="primary" @click="goBatch" :disabled="$refs.table && $refs.table.tableData.length === 0">批量打印 </a-button> -->
        </template>
        <template slot="serial" slot-scope="text, record, index">
          <div style="display: flex;align-items: center;">
            <span style="white-space: nowrap;margin-right:4px"> {{ index + 1 }}</span>
            <span v-if="record.statusName == '待考核'" class="inspection notInspection">待考核</span>
            <span v-else-if="record.statusName == '已考核'" class="inspection alreadyInspection">已考核</span>
            <span v-else-if="record.statusName == '考核中'" class="inspection ingInspection">考核中</span>
            <span v-else-if="record.statusName == '全部已考核'" class="inspection allInspection">全部已考核</span>
          </div>
        </template>
        <template slot="actions" slot-scope="text, record">
          <MoreButton>
            <a v-btnPermission="'pm_022_loo_01'" @click="handleDels(record)">查看</a>
            <a v-if="record.serve === 1 && record.statusName == '待考核'" v-btnPermission="'pm_022_che_05'" @click="handleEdit(record)">考核</a>
            <!--                        <span @click="handleEdit(record)">考核</span>-->
          </MoreButton>
        </template>
      </list-table>
    </a-card>
    <a-modal :visible="visible" title="分包商季度考核" :width="1000" @ok="submitAssessmentOne" @cancel="cancel" cancelText="关闭">
      <div class="about-master-container">
        <a-form-model :model="form" :rules="rules" ref="form">
          <a-row>
            <a-col span="12">
              <a-form-model-item label="考核时间">
                <b-input v-model="form.checkTime" disabled />
              </a-form-model-item>
            </a-col>
            <a-col span="12">
              <a-form-model-item label="实际考核人员">
                <b-input v-model="form.checkUserName" disabled />
              </a-form-model-item>
            </a-col>
            <a-col span="24">
              <a-form-model-item label="诚信建设扣分标准">
                <b-input v-model="form.standard" disabled />
              </a-form-model-item>
            </a-col>
            <a-col span="12">
              <a-form-model-item label="诚信建设分数（15）" prop="standardScore" ref="totalScore">
                <div>
                  <b-input-number :min="0" :max="15" v-model="form.standardScore" placeholder="请输入0-15之间的数字" @change="calcIsShowUpload" />
                  <span>服务类分包商考核只需填写总分</span>
                </div>
              </a-form-model-item>
            </a-col>
            <a-col span="12" v-if="isShowUpload">
              <a-form-model-item label="佐证附件" prop="fileList">
                <BUploadVModel v-model="form.fileList" uploadType="single" businessCode="LCM08" :need-chinese-name="true" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-modal>
  </base-breadcrumb>
</template>

<script>
import moment from 'moment'
import { getQuarterAssessmentList, listTotalQuery, queryBatchButton, serviceUpdate, quarterlyReviewDocPrintBatch } from '@/api/subcontractors/quarterAssessment'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import OrgTreeSelect from '@/components/OrgTreeSelect'
import { getTypes } from '@/api/commons'
import SelectProject from '@/components/Select/SelectProject'
import BUploadVModel from '@/components/BComponents/BUploadVModel'
import api from '@/api/project/typeMaintenance'
import QuarterSelect from '@/views/subcontractors/quarter/QuarterSelect'

export default {
  name: 'a' + Date.now(),
  components: { BUploadVModel },
  data() {
    return {
      htmlData: '打印',
      columns: [
        {
          title: '序号',
          width: 110,
          align: 'center',
          custom: true,
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '分公司',
          width: 100,
          align: 'center',
          dataIndex: 'branch'
        },
        {
          title: '项目名称',
          width: 150,
          align: 'center',
          dataIndex: 'projectName'
        },
        {
          title: '考核分包商名称',
          width: 200,
          align: 'center',
          dataIndex: 'subcontractorName'
        },
        {
          title: '分包商类型',
          width: 200,
          align: 'center',
          dataIndex: 'type'
        },
        {
          title: '考核时间',
          width: 100,
          align: 'center',
          dataIndex: 'assessmentTime',
          scopedSlots: { customRender: 'assessmentTime' }
        },
        {
          title: '考核分数',
          width: 100,
          align: 'center',
          dataIndex: 'assessmentScore'
        },
        {
          title: '考核等级',
          width: 100,
          align: 'center',
          dataIndex: 'assessmentLevel'
        },
        {
          title: '操作',
          dataIndex: 'actions',
          width: 100,
          align: 'center',
          scopedSlots: { customRender: 'actions' }
        }
      ],
      customColumns: [
        {
          title: '序号',
          width: '110px',
          align: 'center',
          custom: true,
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '序号',
          dataIndex: 'statusName'
        },
        {
          title: '分公司',
          width: '100px',
          align: 'center',
          dataIndex: 'branch'
        },
        {
          title: '项目名称',
          width: '150px',
          align: 'center',
          dataIndex: 'projectName'
        },
        {
          title: '考核分包商名称',
          width: '200px',
          align: 'center',
          dataIndex: 'subcontractorName'
        },
        {
          title: '分包商类型',
          width: '200px',
          align: 'center',
          dataIndex: 'type'
        },
        {
          title: '考核时间',
          width: '100px',
          align: 'center',
          dataIndex: 'assessmentTimeName',
          scopedSlots: { customRender: 'assessmentTimeName' }
        },
        {
          title: '考核分数',
          width: '100px',
          align: 'center',
          dataIndex: 'assessmentScore'
        },
        {
          title: '考核等级',
          width: '100px',
          align: 'center',
          dataIndex: 'assessmentLevel'
        },
        {
          title: '操作',
          dataIndex: 'actions',
          width: '100px',
          align: 'center',
          scopedSlots: { customRender: 'actions' }
        }
      ],
      filterData: datas => {
        let list = this.$clone(datas)
        list.forEach((item, index) => {
          item.statusName = index + 1 + item.statusName
        })
        return list
      },
      isShowUpload: false,
      isShowBatchBtn: false,
      form: {
        checkUserName: this.$userInfo().name,
        checkUserId: this.$userInfo().id,
        checkTime: this.$dateFormat(Date.now(), 'Q'),
        fileList: [],
        standardScore: '',
        standard: '不能有效配合现场施工及人员管理的扣5分；出现围堵企业、政府机关等扣10分。',
        assessmentScore: 0
      },
      rules: {
        standardScore: [{ required: true, message: '请输入总分', trigger: 'blur' }],
        fileList: [{ type: 'array', required: true, message: '请上传附件', trigger: 'change' }]
      },
      totalSize: '',
      visible: false,
      searchArr: [
        {
          name: '所属单位',
          valueKey: 'searchQuery',
          type: OrgTreeSelect
        },
        // {
        //   name: '分公司',
        //   valueKey: 'branch',
        //   autoSelected: this.$userType() === 'PD',
        //   type: SelectSubCompany
        // },
        // {
        //   name: '项目名称',
        //   type: SelectProject,
        //   valueKey: 'projectId',
        //   autoSelected: this.$userType() === 'PD',
        //   keyValue: 'branch'
        // },
        {
          name: '分包商名称',
          value: 'subcontractors',
          type: 'input'
        },
        {
          name: '分包商类型',
          value: 'type',
          type: 'tree-select',
          isSeachName: true,
          attrs: {
            allowClear: true,
            replaceFields: { children: 'children', title: 'name', key: 'id', value: 'id' }
          },
          listeners: {
            change(e) {
              console.log(e)
            }
          },
          data: []
        },
        // {
        //   name: '考核时间',
        //   value: 'createdTime',
        //   type: 'monthRange'
        // },
        {
          name: '考核时间',
          valueKey: 'createdTime',
          setInitValue: true,
          initValue: null,
          rangeFormat: ['assessmentStartTime', 'assessmentEndTime'],
          type: QuarterSelect
        },
        {
          name: '考核分数',
          value: '',
          type: 'rangeInput',
          attr: {
            min: 0,
            max: 100
          },
          rangeKey: ['startScore', 'endScore']
        },
        {
          name: '考核分数排序',
          type: 'select',
          value: 'sorted',
          data: [
            {
              label: '分数从低到高',
              value: 0
            },
            {
              label: '分数从高到低',
              value: 1
            }
          ]
        },
        {
          name: '考核等级',
          type: 'select',
          value: 'assessmentLevel',
          data: []
        }
      ],
      titleName: '',
      tableData: [],
      statistics: {},
      temp: s => {
        return (
          <span style="margin-right: 12px">
            分包商总数：<span class="totalNum">{this.statistics.total || 0} 个 </span> | 平均分：<span class="totalNum">{this.statistics.average || 0} </span>
          </span>
        )
      },
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: async parameter => {
        if (this.queryParam.createdTime) {
          this.queryParam = { ...this.queryParam, ...this.queryParam.createdTime }
          delete this.queryParam.createdTime
        }
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        listTotalQuery(requestParameters).then(res => {
          this.statistics.average = res.data.average
        })
        let res = await getQuarterAssessmentList(requestParameters)
        if (res.code === 200) {
          this.statistics.total = res.totalSize
          return { ...res, code: 200 }
        }
        return { code: 500 }
      },
      selectedRowKeys: [],
      selectedRows: [],
      totalDels: {}
    }
  },
  created() {
    this.getTypes()
    this.getIsShowBatchBtn()
    this.getTreeData()
  },
  methods: {
    async getTreeData() {
      let res = await api.labelTreeList()
      if (res.code === 200) {
        this.searchArr[2].data = this.allEnabledDigui(res.data)
      }
    },
    allEnabledDigui(list) {
      let r = []
      list.map(v => {
        v.disabled = false
        if (v.children && v.children.length) {
          v.children = this.allEnabledDigui(v.children)
        }
        r.push(v)
      })
      return r
    },
    async getIsShowBatchBtn() {
      const res = await queryBatchButton()
      if (res.code === 200) {
        this.isShowBatchBtn = res.data == 1
        // this.isShowBatchBtn = true
      }
    },
    calcIsShowUpload(e) {
      this.$refs.totalScore.onFieldBlur()
      if (e === undefined || e === null) return
      this.form.standardScore = Math.round(Number(e))
      if (this.form.standardScore < 9) {
        this.isShowUpload = true
      } else {
        this.isShowUpload = false
      }
    },
    async submitAssessmentOne() {
      this.$refs.form.validate(async v => {
        if (v) {
          this.$submitConfirm(async () => {
            let data = this.$clone(this.form)
            data.baseId = this.form.id
            if (data.fileList.length) {
              data.fileInfoVO = data.fileList[0]
            } else {
              data.fileInfoVO = null
            }
            // delete data.id
            let res = await serviceUpdate(data)
            if (res.code === 200) {
              this.$message.success('操作成功')
              this.$refs.table.refresh(true)
              this.visible = false
            } else {
              this.$message.error(res.message)
            }
          }, '请确认是否要提交，提交后不可修改?')
        } else {
          this.$message.error('请填写完整信息')
        }
      })
    },
    cancel() {
      this.visible = false
      this.form.checkUserName = this.$userInfo().name
      this.form.checkUserId = this.$userInfo().id
      this.form.checkTime = this.$dateFormat(Date.now(), 'Q')
      this.form.fileList = []
      this.form.standardScore = ''
      this.form.assessmentScore = 0
      this.isShowUpload = false
      this.$refs.form.clearValidate()
    },
    goBatch() {
      if (this.$refs.table.tableData.length) {
        this.$nav('/quarter/batchEditAssessment', {
          id: this.$refs.table.tableData[0].id,
          projectName: this.$refs.table.tableData[0].projectName
        })
      } else {
        this.$message.warning('没有列表数据,请先查询')
      }
    },
    // 批量打印
    async handleBatchPrint() {
      const idKeys = this.$refs.table.selectedRowKeys

      if (!idKeys || idKeys.length === 0) {
        this.$warning({ content: '请选择要打印的数据' })
        return Promise.reject()
      }

      if (idKeys.length > 5) {
        this.$warning({ content: '批量打印数量不能超过5条' })
        return Promise.reject()
      }

      try {
        this.$refs.BasePrintButton.loadingState.isPrint = true

        const params = {
          idList: idKeys
        }
        const res = await quarterlyReviewDocPrintBatch(params)
        return res.data.content
      } catch (error) {
        this.$warning({ content: '打印失败' })
        return Promise.reject(error)
      }
    },
    getTypes() {
      getTypes({ type: 16 }).then(res => {
        this.searchArr[6].data = this.getChangeDatatTypes(res.data)
      })
    },
    search(val) {
      this.queryParam = val
      this.$refs.table.refresh(true)
    },
    handleDels(val) {
      let path
      if (val.serve == 1) {
        // if (true) {
        path = '/quarter/serviceDetails'
      } else {
        path = '/quarter/details'
      }
      this.$router.push({
        path,
        query: { assessmentId: val.id, subcontractorName: val.subcontractorName, projectName: val.projectName }
      })
    },
    handleEdit(val) {
      if (val.serve === 1 && val.statusName == '待考核') {
        // if (true) {
        this.form = { ...this.form, ...val }
        if (this.form.assessmentTime) {
          this.form.checkTime = this.form.assessmentTime
        }
        this.visible = true
      } else {
        this.$router.push({
          path: '/quarter/editAssessment',
          query: { assessmentId: val.id, months: val.assessmentTime, name: val.subcontractorName }
        })
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
<style scoped>
.inspection {
  display: inline-block;
  width: 88px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  color: #fff;
  border-radius: 5px;
}

.inspection.notInspection {
  background-color: #ffd700;
}

.inspection.alreadyInspection {
  background-color: #87cefa;
}

.inspection.ingInspection {
  background-color: #ffe4c4;
}

.inspection.allInspection {
  background-color: #00fa9a;
}
</style>
